/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { Button, message } from 'antd';
import classNames from 'classnames';
import { getStorage, setStorage } from '@/utils/storage';
import { noop } from 'lodash';
import styles from './index.less';

const noopPromise = () =>
  new Promise(resolve => {
    // eslint-disable-next-line no-void
    resolve(void 0);
  });

const CaptchaNoRobot = props => {
  const { uniqueId, request, check = noopPromise, className, ...restButtonProps } = props;
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const captchaRef = useRef({});
  const storageKey = uniqueId;

  const rootCls = classNames(styles.captcha, className);
  const isCount = count > 0; // 倒计时中

  function startCount(c) {
    setCount(c);
    if (c > 0) {
      captchaRef.current.timer = setTimeout(() => {
        startCount(c - 1);
        setStorage({
          key: storageKey,
          data: c - 1,
        });
      }, 1000);
    }
  }

  const triggerRequest = params => {
    request(params)
      .then(({ code, msg }) => {
        if (`${code}` === '0') {
          message.success(msg);
          startCount(60);
        } else {
          message.error(msg);
        }
        setLoading(false);
      })
      .catch(err => {
        message.error(err.message);
        setLoading(false);
      });
  };

  const handleClick = () => {
    check()
      .then(() => {
        setLoading(true);
        triggerRequest();
      })
      .catch(() => {});
  };

  useEffect(() => {
    getStorage({ key: storageKey })
      .then(res => {
        const { ts = 0, data } = res || {};
        if (ts === 0) return;
        const diff = Math.max(data - Math.floor((new Date().getTime() - ts) / 1000), 0);
        if (diff > 0) {
          startCount(diff);
        }
      })
      .catch(noop);

    return () => {
      clearTimeout(captchaRef.current.timer);
    };
  }, []);

  return (
    <>
      <Button
        className={rootCls}
        loading={loading}
        disabled={isCount}
        {...restButtonProps}
        onClick={handleClick}
      >
        {isCount ? `${count}秒` : '获取验证码'}
      </Button>
    </>
  );
};

CaptchaNoRobot.defaultProps = {};

export default CaptchaNoRobot;
